package com.example.controller;

import com.example.entity.Person;
import com.example.service.PersonService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/persons")
@RequiredArgsConstructor
public class PersonController {

    private static final Logger log = LoggerFactory.getLogger(PersonController.class);
    private final PersonService personService;

    // 查询所有
    @GetMapping
    public List<Person> getAllPersons() {
        log.info("接收查询所有人员请求");
        return personService.getAllPersons();
    }

    // 根据ID查询
    @GetMapping("/{id}")
    public ResponseEntity<Person> getPersonById(@PathVariable Long id) {
        log.info("接收查询ID为{}的人员请求", id);
        Person person = personService.getPersonById(id);
        return person != null ? ResponseEntity.ok(person) : ResponseEntity.notFound().build();
    }

    // 新增
    @PostMapping
    public ResponseEntity<Boolean> addPerson(@RequestBody Person person) {
        log.info("接收新增人员请求：{}", person);
        boolean success = personService.addPerson(person);
        return success ? ResponseEntity.status(HttpStatus.CREATED).body(true) : ResponseEntity.badRequest().body(false);
    }

    // 更新
    @PutMapping("/{id}")
    public ResponseEntity<Boolean> updatePerson(@PathVariable Long id, @RequestBody Person person) {
        log.info("接收更新ID为{}的人员请求：{}", id, person);
        boolean success = personService.updatePerson(id, person);
        return success ? ResponseEntity.ok(true) : ResponseEntity.notFound().build();
    }

    // 删除
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deletePerson(@PathVariable Long id) {
        log.info("接收删除ID为{}的人员请求", id);
        boolean success = personService.deletePerson(id);
        return success ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build();
    }
}